<?php
namespace Home\Controller;
use Think\Controller;
class AuthMenuController extends CommonController {
    private $model ;
    public function _initialize(){
        $this->model = D("Home/AuthMenu");
    }

    public function index(){
        $count = $this->model->count();
        $page = new \Think\Page($count,20);
        $show =  $page->show();
        $list = $this->model->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        var_dump($page);
        $this->display(); // 输出模板
    }

    public function getMenuById(){
        $id = I("id");
        $data = $this->model->where(array("id"=>$id))->find();
        if(!empty($data)){
            $this->ajaxReturn(1,$data);
        }else{
            $this->ajaxReturn(0,"获取菜单数据失败！");
        }
    }

    public function save(){
        $data = array();
        $data["id"] = I("id",false);
        $data["code"] = I("code");
        $data["name"] = I("name");
        $data["sort"] = I("sort");
        $data["statue"] = I("statue");
        //$data["icon"] = I("icon");
        if(empty($data["id"])){
            $this->add($data);
        }else{
            $this->edit(data);
        }
    }

    private function add($data){
        $condition = array("code"=>$data["code"]);
        if($this->model->where($condition)->count()>0){
            $this->ajaxReturn(0,"菜单编号重复！");
        }
        $condition = array("name"=>$data["name"]);
        if($this->model->where($condition)->count()>0){
            $this->ajaxReturn(0,"菜单名称重复！");
        }
        $addResult = $this->model->add($data);
        if(!$addResult){
            $this->ajaxReturn(0,"保存失败！");
        }else{
            $this->ajaxReturn(1,"保存成功！");
        }
    }

    private function edit($data){
        $condition = array();
        $condition["id"] = array("neq"=>$data["id"]);
        $condition["code"] = $data["code"];
        if($this->model->where($condition)->count()>0){
            $this->ajaxReturn(0,"菜单编号重复！");
        }
        unset($condition["code"]);
        $condition["name"] = $data["name"];
        if($this->model->where($condition)->count()>0){
            $this->ajaxReturn(0,"菜单名称重复！");
        }
        $editResult = $this->model->add($data);
        if($editResult==0){
            $this->ajaxReturn(0,"无数据更新");
        }else if($editResult===false){
            $this->ajaxReturn(0,"保存失败！");
        }else{
            $this->ajaxReturn(1,"保存成功");
        }
    }
}